--basically, this script nicks all the weapons we are interested in, and puts them into tables
--we're going to also be messing with these weapons, adding new k/v pairs relaing to ownership.

GM.CombatWeapons = {
	{}, --primary
	{}, --secondary
	{}, --support
	{}, --grenades (special!)
}

GM.PurchasePerUnitWeapons = {

}

local function ConvertSlot (slot)
	if slot == 2 then slot = 1 elseif slot == 1 then slot = 2 end --swap primary/secondary (we want secondary to be first in the HL2 weapon select menu, but don't want it to be first here)
	return slot
end

function GM:InitializeWeaponLists ()
	for _,wpn in pairs (weapons.GetList()) do --our knowledge of every Lua weapon been loaded into the game.
		if wpn.Cost then --we're only interested in weapons that have a cost - only they are purchasable
			table.insert (self.CombatWeapons[ConvertSlot(wpn.Slot)], wpn)
			if CLIENT then
				wpn.Licensed = false
				wpn.Active = false
			end
		end
	end
	for k,v in pairs (self.CombatWeapons) do
		table.sort (v, function(a,b) return a.Cost < b.Cost end)
	end
end

GM:AddHook ("Initialize", "InitializeWeaponLists")

local function RecvWeaponLicenses (umsg)
	printd ("recv")
	while umsg:ReadBool() do
		local wpntype = umsg:ReadShort()
		printd ("wpntype", wpntype)
		while umsg:ReadBool() do
			local wpnid = umsg:ReadShort()
			printd ("wpnid", wpnid)
			GAMEMODE.CombatWeapons[wpntype][wpnid].Licensed = true
		end
	end
end

usermessage.Hook ("WpnLicenses", RecvWeaponLicenses)

local function RecvWeaponLicense (umsg)
	local wpntype = umsg:ReadShort()
	local wpnid = umsg:ReadShort()
	GAMEMODE.CombatWeapons[wpntype][wpnid].Licensed = true
end

usermessage.Hook ("WpnLicense", RecvWeaponLicense)

local function RecvWeaponUnits (umsg)
	local wpntype = umsg:ReadShort()
	local wpnid = umsg:ReadShort()
	GAMEMODE.CombatWeapons[wpntype][wpnid].Units = umsg:ReadShort()
end

usermessage.Hook ("WpnUnits", RecvWeaponUnits)

local function RecvActiveWeapon (umsg)
	local wpntype = umsg:ReadShort()
	local wpnid = umsg:ReadShort()
	for id,tbl in pairs (GAMEMODE.CombatWeapons[wpntype]) do
		tbl.Active = id == wpnid
	end
end

usermessage.Hook ("WpnActive", RecvActiveWeapon)
